let vm = new Vue({
    el: "#app",
    data: {
        total: 0,
        count: 0,
        search: "",
        isLogin: false, // 是否登录
        user: {}, // 用户的信息
        carts: [] // 购物车
    },
    created: function () {
        // 获取登录的用户信息
        axios.get("/user/getlogin").then(function (response) {
            vm.user = response.data;
            vm.isLogin = response.data !== "";
        }).catch();

        // 查询查询用户的购物车
        axios.get("/shop_cart/select").then(function (response) {
            vm.count = 0;
            vm.total = 0;
            vm.carts = response.data;

            for (let i = 0; i < vm.carts.length; i++) {
                let cart = vm.carts[i];

                vm.count += cart.quantity;
                vm.total += cart.money;
            }
        }).catch();
    },
    methods: {
        query() { // 查询商品
            location.href = "/list.html?name=" + vm.search;
        },
        del(id) { // 删除购物车
            let bool = confirm("是否确认删除？");

            if (bool) {
                axios.get("/shop_cart/deleteById/" + id).then(function (response) {
                    let result = response.data;

                    if (result.code === 200) {
                        // 查询查询用户的购物车
                        axios.get("/shop_cart/select").then(function (response) {
                            vm.count = 0;
                            vm.total = 0;
                            vm.carts = response.data;

                            for (let i = 0; i < vm.carts.length; i++) {
                                let cart = vm.carts[i];

                                vm.count += cart.quantity;
                                vm.total += ((cart.money * 100) * cart.quantity) / 100;
                            }
                        }).catch();
                    } else {
                        alert(result.msg);
                    }
                }).catch();
            }
        },
        logout() { // 退出登录
            axios.get("/user/logout").then(function (response) {
                let result = response.data;

                if (result.code === 200) {
                    location.href = "/login.html";
                } else {
                    alert(result.msg);
                }
            }).catch();
        }
    }
});